package com.javasm.common.utils;

import java.security.SecureRandom;

public class RandomStringGenerator {

    private static final String CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String NUMBERCHARACTERS = "0123456789";
    private static final SecureRandom RANDOM = new SecureRandom();
    private static  String codeRandom=null;
    public static String getCodeRandom() {
        return codeRandom;
    }

    /**
 * 生成指定长度的随机字符串
 *
 * @param length 随机字符串的长度
 * @return 生成的随机字符串
 * @throws IllegalArgumentException 如果指定的长度为负数
 */
public static String generateRandomString(int length) {


    // 检查长度是否为负数，如果是则抛出异常
    if (length < 0) {
        throw new IllegalArgumentException("Length must be non-negative");
    }

    // 创建一个StringBuilder对象，初始容量为指定的长度
    StringBuilder stringBuilder = new StringBuilder(length);
    // 循环生成随机字符并添加到StringBuilder中，直到达到指定长度
    for (int i = 0; i < length; i++) {
        int index = RANDOM.nextInt(CHARACTERS.length());
        stringBuilder.append(CHARACTERS.charAt(index));
    }
    // 返回生成的随机字符串
    return stringBuilder.toString();
}
    /**
     * 生成指定长度的随机数字字符串，且第一位不能是0
     *
     * @param length 随机数字字符串的长度
     * @return 生成的随机数字字符串
     * @throws IllegalArgumentException 如果指定的长度为负数或0
     */
    public static String generateRandomNumberString(int length) {
        // 检查长度是否为负数或0，如果是则抛出异常
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be positive");
        }

        // 创建一个StringBuilder对象，初始容量为指定的长度
        StringBuilder stringBuilder = new StringBuilder(length);

        // 生成第一位数字，确保不是0
        int firstDigitIndex = RANDOM.nextInt(9) + 1; // 1到9之间的随机数
        stringBuilder.append(NUMBERCHARACTERS.charAt(firstDigitIndex));

        // 生成剩余的随机数字
        for (int i = 1; i < length; i++) {
            int index = RANDOM.nextInt(NUMBERCHARACTERS.length());
            stringBuilder.append(NUMBERCHARACTERS.charAt(index));
        }

        // 返回生成的随机数字字符串
        codeRandom = stringBuilder.toString();

        return codeRandom;
    }



    public static void main(String[] args) {
        int length = 10; // 示例长度
        String randomString = generateRandomString(length);
        System.out.println("随机字符串: " + randomString);
    }
}
